package com.example.demo.model;


import com.example.demo.core.exception.ProgramException;
import com.example.demo.core.util.LockUtil;
import com.example.demo.core.util.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author yj
 * @date 2021/4/1 16:00
 */
public class OrderRunnable implements Runnable {

    private Logger logger = LoggerFactory.getLogger(OrderRunnable.class);

    private volatile Integer num;

    public OrderRunnable(Integer num) {
        if (num == null){
            throw new ProgramException("参数不能为空");
        }
        if (num == 0){
            throw new ProgramException("参数不能为0");
        }
        this.num = num;
    }

    public OrderRunnable() {
        this.num = 100;
    }

    @Override
    public void run() {
        while (num > 0) {
            ThreadUtil.sleep(10);
            LockUtil.lock();
            try {
                if (num > 0) {
                    int temp = num;
                    temp--;
                    num = temp;
                    System.out.println(ThreadUtil.getThreadName() + "卖出第" + (num) + "张票");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                LockUtil.unLock();
            }
        }
    }
}